package com.jm.dao;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Query;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.jm.entity.Agenttype;
import com.jm.entity.Orderitem;
import com.jm.entity.Product;
import com.jm.entity.ProductAgent;
import com.jm.viewmodel.User;
import com.jm.viewmodel.ViewProduct;
import com.opensymphony.xwork2.util.logging.log4j2.Log4j2Logger;
import com.sun.jmx.snmp.SnmpStatusException;

public class ManagerDao {
	 
	public class AgentsPrice{
		private String agentypeid;
		private String cost;
		public String getAgentypeid() {
			return agentypeid;
		}
		public void setAgentypeid(String agentypeid) {
			this.agentypeid = agentypeid;
		}
		public String getCost() {
			return cost;
		}
		public void setCost(String cost) {
			this.cost = cost;
		}
		
	}
	/***
	 * 管理员新增产品
	 * @param pname
	 * @param pdescribe
	 * @param picurl
	 * @param total
	 * @param allagentsprice
	 * @return
	 */
	public Long addProduct(String pname,String pdescribe,String picurl,double total,String allagentsprice){
		System.out.println(allagentsprice);
		String[]aPrices = allagentsprice.split(",");
		List<AgentsPrice>mAPList = new ArrayList<>();
		for(int i=0;i<aPrices.length;i++){
			AgentsPrice agentsPrice = new AgentsPrice();
			agentsPrice.setAgentypeid(String.valueOf(i+2));
			agentsPrice.setCost(aPrices[i]);
			System.out.println(agentsPrice.getCost());
			mAPList.add(agentsPrice);
		}
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		Product product = new Product();

		Set<ProductAgent>productAgents = new HashSet<>();
		for(AgentsPrice agentsPrice : mAPList){
			ProductAgent productAgent = new ProductAgent();
			productAgent.setCost(BigDecimal.valueOf(Long.valueOf(agentsPrice.getCost())));
			Agenttype agenttype = new Agenttype();
			agenttype.setTypeid(Integer.valueOf(agentsPrice.getAgentypeid()));
			productAgent.setAgenttype(agenttype);
			productAgent.setProduct(product);
			mSession.save(productAgent);
			productAgents.add(productAgent);
		}
		product.setProductAgents(productAgents);
		product.setPicurl(picurl);
		product.setTotal(Double.valueOf(total));
		product.setPdescribe(pdescribe);
		product.setPname(pname);
		
		
		Serializable result = mSession.save(product);
		tx.commit();
		
		Long count = (Long) result;
		System.out.println("add product result ...."+count);
		
		mSession.close();
//		mSessionFactory.close();
		return count;
	}
	
	
	
	
	/***
	 * 查询所有产品信息
	 * @return
	 */
	public List<ViewProduct> getProducts(){
		List<ViewProduct>products = new ArrayList<>();
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		String hql = "select p from com.jm.entity.Product p";
		@SuppressWarnings("unchecked")
		List<Product> pList = mSession.createQuery(hql).list();
		if (pList!=null && pList.size()>0){
			for(Product p : pList){
				ViewProduct viewProduct = new ViewProduct();
				viewProduct.setPdescribe(p.getPdescribe());
				viewProduct.setPicurl(p.getPicurl());
				viewProduct.setPname(p.getPname());
				viewProduct.setTotal(p.getTotal());
				viewProduct.setPid(p.getPid());
				Set<ProductAgent> pAgents = p.getProductAgents();
				if(pAgents.size()>0){
					List<AgentsPrice>mAgentsPrices = new ArrayList<>();
					for(ProductAgent pa : pAgents){
						AgentsPrice mAgentsPrice = new AgentsPrice();
						mAgentsPrice.setAgentypeid(String.valueOf(pa.getAgenttype().getTypeid()));
						mAgentsPrice.setCost(String.valueOf(pa.getCost()));
						mAgentsPrices.add(mAgentsPrice);
						
					}		
					viewProduct.setMaAgentsPrice(mAgentsPrices);
				}				
				products.add(viewProduct);
			}
		}
		
		mSession.close();
//		mSessionFactory.close();
		return products;
	}
	
	/***
	 * 编辑产品信息 会连带更新各级代理价格
	 * @param pid
	 * @param pname
	 * @param pdescribe
	 * @param picurl
	 * @param total
	 * @param allagentsprice
	 * @return
	 */
	public int editProduct(Long pid,String pname,String pdescribe,String picurl,double total,String allagentsprice){
		String[]aPrices = allagentsprice.split(",");
		List<AgentsPrice>mAPList = new ArrayList<>();
		for(int i=0;i<aPrices.length;i++){
			AgentsPrice agentsPrice = new AgentsPrice();
			agentsPrice.setAgentypeid(String.valueOf(i+2));
			agentsPrice.setCost(aPrices[i]);
			System.out.println(agentsPrice.getCost());
			mAPList.add(agentsPrice);
		}

		
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		List<Product> mProduct = mSession.createQuery("from com.jm.entity.Product p where pid=:pid").setParameter("pid", pid).list();
		int ret = 0;
		if(mProduct.size()>0){
			Product product = mProduct.get(0);
			Set<ProductAgent>productAgents = product.getProductAgents();
			
			for (ProductAgent productAgent : productAgents) {
				for(AgentsPrice agentsPrice : mAPList){
					if (String.valueOf(productAgent.getAgenttype().getTypeid()).equals(agentsPrice.getAgentypeid())){
						Agenttype agenttype = new Agenttype();
						agenttype.setTypeid(Integer.valueOf(agentsPrice.getAgentypeid()));
						productAgent.setAgenttype(agenttype);
						productAgent.setCost(BigDecimal.valueOf(Double.valueOf(agentsPrice.getCost())));
					}
				}
			}
			product.setPdescribe(pdescribe);
			if(picurl != ""){
				product.setPicurl(picurl);
			}
			product.setPname(pname);
			product.setProductAgents(productAgents);
			product.setTotal(total);
			mSession.saveOrUpdate(product);
			ret = 1;
		}
		
		mSession.flush();
		tx.commit();
		mSession.close();
//		mSessionFactory.close();
		return ret;
	}
	
	public int deleteProduct(long pid){
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		@SuppressWarnings("unchecked")
		List<ProductAgent>pAgents = mSession.createQuery("from com.jm.entity.ProductAgent pa where pid=:pid").setParameter("pid", pid).list();
		if(pAgents!=null &&pAgents.size()>0){
			return -1;
		}
		
		@SuppressWarnings("unchecked")
		List<Product> mProduct = mSession.createQuery("from com.jm.entity.Product p where pid=:pid").setParameter("pid", pid).list();
		int ret = 0;
		if(mProduct.size()>0){
			Product product = mProduct.get(0);
			mSession.delete(product);
			ret = 1;
		}
//		mSession.flush();
		tx.commit();
		mSession.close();
//		mSessionFactory.close();
		return ret;
	}

	/***
	 * 获取可以升级的用户
	 * @return
	 */
	public List<User> getCanLevelUp(){
		List<User>lupUsers = new ArrayList<>();
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		String sql = "from com.jm.entity.User u where u.examinelevelstatue = 1";
		List<com.jm.entity.User>users = mSession.createQuery(sql).list();
		if(users!=null && users.size()>0){
			for (com.jm.entity.User user : users) {
				if(user.getAgenttype().getTypeid()>user.getCanupgradelevel()){
					User vUser = new User();
					vUser.setAgenttypeid(user.getAgenttype().getTypeid());
					vUser.setAgenttypename(user.getAgenttype().getTypename());
					vUser.setUserid(user.getUserid());
					vUser.setNickname(user.getName());
					vUser.setCanupgradelevel(user.getCanupgradelevel());
					lupUsers.add(vUser);
				}
			}
		}
		mSession.close();
//		mSessionFactory.close();
		return lupUsers;
	}
	/***
	 * 根据用户id，判断该用户是否可以升级
	 * @param uid
	 * @return
	 */
	public int getCanLevelUpByUserId(long uid){
		int result = 0;
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		String sql = "from com.jm.entity.User u where  u.userid =:uid";
		@SuppressWarnings("unchecked")
		List<com.jm.entity.User>users = mSession.createQuery(sql).setParameter("uid", uid).list();
		if(users!=null && users.size()>0){
			com.jm.entity.User user = users.get(0);
			if(user.getAgenttype().getTypeid()>user.getCanupgradelevel()){
				int staue;
				if(user.getExaminelevelstatue() == null){ staue = 0;}
				else
				staue = user.getExaminelevelstatue();
				int upTypeid = user.getCanupgradelevel();
				if(staue==1){
					result = 100+upTypeid ;  //审核中
				}else if (staue ==0) {
					result = 200+upTypeid;
				}else if (staue == 2) {
					result = 0;
				}
			}
		}
		mSession.close();
//		mSessionFactory.close();
		return result;
	}
	
	public boolean requestUpgradeByUid(long uid){
		System.out.println(String.valueOf(uid));
		boolean result = false;
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		String sql = "from com.jm.entity.User u where u.userid =:uid";
		@SuppressWarnings("unchecked")
		List<com.jm.entity.User>users = mSession.createQuery(sql).setParameter("uid", uid).list();
		System.out.println(String.valueOf(users.size()));
		if(users!=null && users.size()>0){
			
			try {
				com.jm.entity.User user = users.get(0);
				user.setExaminelevelstatue(1);
				mSession.saveOrUpdate(user);
				mSession.flush();
				tx.commit();
				result = true;
			} catch (Exception e) {
				// TODO: handle exception
				tx.rollback();
				result = false;
			}finally {
				mSession.close();
//				mSessionFactory.close();
			}
			
		}
		
		return result;
	}
	
	public boolean examineLevelUp(boolean isPass,long uid){
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		String sql = "from com.jm.entity.User u where u.userid =:uid";
		@SuppressWarnings("unchecked")
		List<com.jm.entity.User>users = mSession.createQuery(sql).setParameter("uid", uid).list();
		if(users!=null && users.size()>0){
			try {
				com.jm.entity.User user = users.get(0);
				Agenttype agenttype = new Agenttype();
				agenttype.setTypeid(user.getCanupgradelevel());
				user.setAgenttype(agenttype);
				user.setAgenttypename("");//只要升级这个agentName无效
				user.setExaminelevelstatue(2);//2代表已经审核通过，0表示初始态,1代表用户自己发起申请
				mSession.saveOrUpdate(user);
				mSession.flush();
				tx.commit();
				return true;
			} catch (Exception e) {
				// TODO: handle exception
				tx.rollback();
				return false;
			}finally {
				mSession.close();
//				mSessionFactory.close();
			}
			
		}
		
		return false;
	}
	
	public List<User> getAgentsOfArea(int areaid,long uid){
		List<User>vUsers = new ArrayList<>();
		try {
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
			Session mSession = mSessionFactory.openSession();
			Transaction tx = mSession.beginTransaction();
			String sql = "from com.jm.entity.User u where  u.authorizedpersonid =:uid";
			@SuppressWarnings("unchecked")
			List<com.jm.entity.User>users = mSession.createQuery(sql).setParameter("uid", uid).list();
			if (users!=null && users.size()>0) {
				for (com.jm.entity.User user : users) {
					if (user.getArea().getAreaid()==areaid) {
						User vUser = new User();
						vUser.setNickname(user.getName());
						vUser.setAgenttypeid(user.getAgenttype().getTypeid());
						vUser.setAgenttypename(user.getAgenttype().getTypename());
						vUser.setUserid(user.getUserid());
						vUsers.add(vUser);
					}
				}
			}
			mSession.flush();
			mSession.close();
			
//			mSessionFactory.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("error error!!!!!!");
		}
		
		return vUsers;
	}
}
